package cn.javacart.jopencart.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * Opencat转换器
 * @author farmer
 *
 */
public class JOpencartPhpUrlFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		chain.doFilter(new HttpServletRequestWrapper(req){
			@Override
			public String getRequestURI() {
				String requestURI = super.getRequestURI();
				if("/".equals(requestURI)){
					requestURI = "/index.php";
				}
				if("/index.php".equals(requestURI)){
					String route = getParameter("route");
					if("".equals(route)||route == null){
						route = "/common/home";
					}
					if(!route.startsWith("/")){
						route = "/".concat(route);
					}
					return route; 
				}
				return requestURI;
			}
		}, response);
	}

	@Override
	public void destroy() {
	}

}
